package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"net/rpc"
	"net/rpc/jsonrpc"
)
const HelloServiceName = "path/to/pkg.HelloService"


type HelloService struct {

}

type HelloServiceInterface = interface {
	Hello(request string, reply *string) error
}



func (p *HelloService) Hello(request string, reply *string) error {
	*reply = "hello:" + request
	fmt.Println("接收到请求:",request)
	return nil
}

var (
	f string
)

func init()  {
	flag.StringVar(&f, "f", "", "")

}

func main()  {
	flag.Parse()

	switch f {
	case "server":
		server()
	case "client":
		client()
	case "serverhttp":
		serverhttp()
	}

}

func server() {
	//注册函数
	if err:=rpc.RegisterName("HelloService",new(HelloService));err!= nil {
		log.Fatal("RegisterName error:", err)
	}
	listener,err:=net.Listen("tcp",":1234")
	if err != nil {
		log.Fatal("ListenTCP error:", err)
	}
	for {
		conn,err:=listener.Accept()
		if err!= nil {
			log.Fatal("Accept error:", err)
		}

		go rpc.ServeCodec(jsonrpc.NewServerCodec(conn))
	}

}

func serverhttp() {
	//注册函数
	if err:=rpc.RegisterName("HelloService",new(HelloService));err!= nil {
		log.Fatal("RegisterName error:", err)
	}

	http.HandleFunc("/jsonrpc", func(w http.ResponseWriter, r *http.Request) {
		var conn io.ReadWriteCloser= struct {
			io.Writer
			io.ReadCloser
		}{
			ReadCloser: r.Body,
			Writer:w,
		}

		rpc.ServeRequest(jsonrpc.NewServerCodec(conn))

		
	})

	http.ListenAndServe(":1234",nil)
	c:=make(chan int)

	<-c

}

func client()  {
	conn,err:=net.Dial("tcp","localhost:1234")
	if err != nil {
		panic(err)
	}

	client:= rpc.NewClientWithCodec(jsonrpc.NewClientCodec(conn))
	var reply string
	err=client.Call("HelloService.Hello","hello",&reply)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(reply)


}